// pages/UCenter/index/index.js
import * as socketUtil from '../../../api/socketUtil'
import * as API_SYSConfig from "../../../api/sysConfig";
import * as API_Mall_Integral from "../../../api/mall/integral"
import * as API_Coupon from '../../../api/coupon'
import * as API_Collect from '../../../api/collect'
import * as API_Member from '../../../api/member'
import * as util from '../../../utils/util'
const config = require('../../../utils/config.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    servicePhone: '',
    phoneX: "",
    integral: 0,
    couponsParams: {
      pageNum: 1,
      pageSize: 1,
      canUseState: 'Y',
      useState: 'N',
    },
    couponsNum: 0,
    collectNum: 0,
    section2List: [
      {
        icon: '/static/img/42.png',
        title: '待付款',
        state: 'wait_pay',
        id: 1
      },{
        icon: '/static/img/43.png',
        title: '待使用',
        state: 'wait_use',
        id: 2
      },{
        icon: '/static/img/44.png',
        title: '待售后',
        state: 'aftersale',
        id: 3
      },{
        icon: '/static/img/45.png',
        title: '待评价',
        state: 'wait_comment',
        id: 4
      },{
        icon: '/static/img/46.png',
        title: '退款',
        state: 'refund_success',
        id: 5
      }
    ],
    section3List: [
      {
        icon: '/static/img/47.png',
        title: '我的预约',
        url: '../../appointmentRecord/appointmentRecord',
        type: 'nav'
      },
      {
        icon: '/static/images/8.png',
        title: '上门服务',
        url: '/pages/doorlist/doorlist',
        type: 'nav'
      },
      {
        icon: '/static/img/48.png',
        title: '我的收藏',
        url: '../../collectList/collectList',
        type: 'nav'
      },{
        icon: '/static/img/49.png',
        title: '我的足迹',
        url: '../../footprint/footprint',
        type: 'nav'
      },{
        icon: '/static/img/50.png',
        title: '优惠劵',
        url: '/pages/myCoupons/myCoupons',
        type: 'nav'
      },{
        icon: '/static/img/51.png',
        title: '分享得积分',
        type: 'fun',
        function: 'switchModal'
      },{
        icon: '/static/img/52.png',
        title: '在线客服',
        type: 'contact'
      },{
        icon: '/static/img/53.png',
        title: '手型选择',
        url: '/pages/shapeSelect/shapeSelect?type=0',
        type: 'nav'
      },{
        icon: '/static/img/54.png',
        title: '脸型选择',
        url: '/pages/shapeSelect/shapeSelect?type=1',
        type: 'nav'
      },{
        icon: '/static/img/55.png',
        title: '平台热线',
        type: 'fun',
        function: 'callPhone'
      },{
        icon: '/static/img/56.png',
        title: '意见反馈',
        url: '../opinion/opinion',
        type: 'nav'
      }
    ],
    modalStatus: false,
    modalData: {},
    shareData: {
      userNum: 0,
      integral: 0
    },
    showus: false
  },
  handleShowUs() {
    this.setData({
      showus: true
    })
    wx.hideTabBar({
      animation: true,
    })
  },
  handleHideUs() {
    this.setData({
      showus: false
    })
    wx.showTabBar({
      animation: true,
    })
  },
  updateMember () {
    const query = this.selectComponent("#member-info")
    query.setData({
      showDialog: false,
      showInput: true,
      showClose: true,
      avatarUrl: this.data.userInfo.headImg,
      nickName: this.data.userInfo.nickName
    })
  },
  saveCode () {
    wx.downloadFile({
      url: this.data.modalData.belowImageUrl,
      success: (res) => {
        if (res.statusCode === 200) {
          let tempFilePath = res.tempFilePath
          wx.saveImageToPhotosAlbum({
            filePath: tempFilePath,
            success: () => {
              wx.showToast({
                title: '保存成功！',
                icon: 'none'
              })
            }
          })
        }
      }
    })
  },
  getShareImg () {
    if (this.data.userInfo.belowImageUrl) {
      this.setData({
        'modalData.belowImageUrl': this.data.userInfo.belowImageUrl,
        modalStatus: !this.data.modalStatus
      })
    } else {
      getApp().https.ajax({
        method: 'post',
        url: '/member/refreshStoreBelow',
        loading: true,
      }).then(({ data }) => {
        this.setData({
          'userInfo.belowImageUrl': data.belowImageUrl,
          'modalData.belowImageUrl': data.belowImageUrl,
          modalStatus: !this.data.modalStatus
        })
      })
    }
  },
  switchModal () {
    if (this.data.modalStatus) {
      this.setData({
        modalStatus: false
      })
    } else {
      getApp().https.ajax({
        method: 'post',
        url: '/member/getUserNumAndIntegral',
        loading: true,
      }).then(({ data }) => {
        this.setData({
          shareData: data
        })
        this.getShareImg()
      })
    }
  },
  handleClick (e) {
    let index = e.currentTarget.dataset.index
    let data = this.data.section3List[index]
    if (data.type === 'nav') {
      wx.navigateTo({
        url: data.url
      })
    }
    if (data.type === 'fun') {
      this[data.function]()
    }
  },
  // 跳转全部订单页
  goMyOrderList(e) {
    wx.navigateTo({
      url: '/pages/myOrderList/myOrderList?state=' + e.currentTarget.dataset.state + '&tabIndex=' + e.currentTarget.dataset.tab_index,
    })
  },
  // 平台热线
  callPhone() {
    wx.makePhoneCall({
      phoneNumber: this.data.servicePhone + ''
    })
  },
  toMember () {
    wx.navigateTo({
      url: '/pages/member/member',
    })
  },
  // 跳转我的地址页
  goAddress() {
    wx.navigateTo({
      url: '../../mall/receAddressList/receAddressList',
    })
  },
  RECEIVE_MSG_INFORM: function (json) {
    //收到新消息
    let reqParam = {};
    socketUtil.sendData("MY_MSG_UNREAD_COUNT", reqParam);
  },
  MY_MSG_UNREAD_COUNT: function (json) {
    let unreadMsgCount = json.info.unreadMsgCount;
    if (unreadMsgCount == 0) {
      wx.removeTabBarBadge({
        index: 1
      })
    } else {
      wx.setTabBarBadge({
        index: 1,
        text: unreadMsgCount + ''
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if(options.scene){
      const scene = decodeURIComponent(options.scene)
      let sceneJso=util.getUrlVars(scene)
      wx.setStorageSync('storeId',sceneJso.bindId)
      wx.setStorageSync('storeUserId',sceneJso.storeUserId)
      wx.setStorageSync('bindMemberId',sceneJso.bindMemberId)
    }
    let statusBarHeight = getApp().globalData.statusBarHeight;
    this.setData({
      statusBarHeight: statusBarHeight
    })
    API_SYSConfig.getValueByKey("service_phone").then(res => {
      this.setData({
        servicePhone: res
      });
    });

    this.flushLogin();
    // wx.hideTabBar()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  // 跳转积分页
  gotoIntegral() {
    let total = this.data.integral
    wx.navigateTo({
      url: '../../integralHome/integralHome?total=' + total,
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    getApp().watch(this.MY_MSG_UNREAD_COUNT, 'MY_MSG_UNREAD_COUNT') //注册监听
    getApp().watch(this.RECEIVE_MSG_INFORM, 'RECEIVE_MSG_INFORM') //注册监听
    let reqParam = {};
    socketUtil.sendData("MY_MSG_UNREAD_COUNT", reqParam);
    this.flushInfo();

    this.flushIntegral()
    this.flushCoupons()
    this.flushCollect()
    let state = getApp().globalData.toIndex
    if (state) {
      getApp().globalData.toIndex = false
      wx.navigateTo({
        url: '/pages/myOrderList/myOrderList?state=wait_ship&tabIndex=2',
      })
    }
  },
  flushCollect() {
    let params = {
      collectType: 'product',
      pageNum: 1,
      pageSize: 1,
    }
    API_Collect.getList(params).then(res => {
      this.setData({
        collectNum: res.data.total
      })
    })
  },
  flushCoupons() {
    API_Coupon.getList(this.data.couponsParams).then(res => {
      this.setData({
        couponsNum: res.data.total
      })
    })
  },
  flushIntegral() {
    API_Mall_Integral.getTotal().then(res => {
      this.setData({
        integral: res.data
      })
    })
  },
  flushInfo() {
    const member = wx.getStorageSync('member')
    let phoneX = member.phone;
    if (phoneX) {
      phoneX = phoneX.substring(0, 3) + "****" + phoneX.substring(7)
    } else {
      phoneX = "授权手机号";
    }
    this.setData({
      userInfo: member,
      phoneX: phoneX
    })
  },
  getPhone: function (e) {
    let that = this;
    if (!e.detail.iv) {
      //认为用户拒绝了或者关闭了授权 
      this.setData({
        phoneHasRefuse: true
      })
      wx.showToast({
        title: '为了更好的为您服务，请同意授权手机号',
        icon: 'none'
      })
      return;
    }
    const params = {
      encryptedData: e.detail.encryptedData,
      iv: e.detail.iv,
      code: this.data.wxlogincode,
      APPKEY: config.APPKEY
    }
    API_Member.flushPhone(params).then(res => {
      if (res.success || res.exist) {
        wx.setStorageSync('member', res.member)
        wx.setStorageSync('token', res.token)
        this.setData({
          showDialog: true
        })
        wx.showTabBar({
          animation: true,
        })

      }
      that.flushLogin();
      that.flushInfo();
    })


  },
  flushLogin: function () {
    //因为这个code只能用一次，使用一次后需要刷新下
    let that = this;
    wx.login({
      timeout: 8000,
      success(res) {
        that.setData({
          wxlogincode: res.code
        });

      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})